package com.platform.apex.cma.config;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValue;
import com.typesafe.config.ConfigValueType;

public class ConfigLoader {

	public static TypesafeConfig loadResource() {
		String resourceFile = "application.conf";
		return loadResource(resourceFile);
	}

	public static TypesafeConfig loadResource(String resource) {
		Map<String, String> subConf = new HashMap<String, String>();
		Config config = ConfigFactory.load(resource);

		Iterator<Entry<String, ConfigValue>> configIterator = config.entrySet().iterator();
		while (configIterator.hasNext()) {
			Entry<String, ConfigValue> eachEntry = configIterator.next();
			ConfigValue configValue = eachEntry.getValue();
			if (configValue.valueType().compareTo(ConfigValueType.STRING) == 0) {
				String configValueStr = eachEntry.getValue().unwrapped().toString();
				if (configValueStr.startsWith("location")) {
					String realPath = configValueStr.replace("location", "").replace("(", "").replace(")", "")
							.replace("\"", "");
					subConf.put(eachEntry.getKey(), realPath);
				}
			}
		}

		Config baseConfig = null;

		if (subConf.size() > 0) {
			for (Entry<String, String> eachOne : subConf.entrySet()) {
				Config eachConfig = ConfigFactory.load(eachOne.getValue().trim());
				if (null == baseConfig) {
					baseConfig = eachConfig;
				} else {
					baseConfig = baseConfig.withFallback(eachConfig);
				}
			}
		}

		if (null == baseConfig) {
			baseConfig = config;
		} else {
			baseConfig = baseConfig.withFallback(config);
		}

		TypesafeConfig typesafeConfig = new TypesafeConfig(baseConfig.resolve());
		return typesafeConfig;
	}
}
